package server

import (
	"net/http"
	"server/internal/core/constant"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

type ResponseData struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data"`
	TraceID string `json:"trace_id,omitempty"`
}

type Controller struct{}

func (c Controller) Success(ctx *gin.Context, data any) {
	c.Response(ctx, &ResponseData{
		Code:    http.StatusOK,
		Message: "success",
		Data:    data,
	})
}

func (c Controller) Error(ctx *gin.Context, err error) {
	// 默认错误码和消息
	code := UnknownError.Code
	message := UnknownError.Message

	// 如果错误是ApiError，则使用错误码和消息
	if apiErr, ok := err.(*ApiError); ok {
		code = apiErr.Code
		message = apiErr.Message
	}

	//如果是验证错误，则使用验证错误码和消息
	if validationErrors, ok := err.(validator.ValidationErrors); ok {
		code = http.StatusUnprocessableEntity
		message = "参数验证失败"
		for _, validationError := range validationErrors {
			message += validationError.Error() + ","
		}
		message = strings.TrimSuffix(message, ",")
	}

	c.Response(ctx, &ResponseData{
		Code:    code,
		Message: message,
		Data:    nil,
	})
}

func (c Controller) Response(ctx *gin.Context, resp *ResponseData) {
	if resp.TraceID == "" {
		resp.TraceID = ctx.GetString(constant.TraceIDKeyType{})
	}
	ctx.JSON(http.StatusOK, resp)
}

var DefaultController = Controller{}
